window.upload = function(arg) {
	var upload = layui.upload2;
	upload.render({
		elem: arg.elem,
		url: arg.url,
		accept: arg.accept,
		exts: arg.exts,
		multiple: false,
		auto: false,
		bindAction: arg.bindAction,
		choose: function(obj) {
			var _this = this;
			obj.preview(function(index, file, result) {
				_this.elem[0].innerHTML = file.name + '';
			});
			arg.choose && arg.choose.apply(this, obj);
		},
		done: arg.done,
		error: arg.error
	});
};

window.uploadPreview = function(arg) {
	$(arg.elem).addClass('layui-upload-1').get(0).innerHTML =
		'<div class="layui-upload-list">' +
		'	<span class="upload-bg"></span>' +
		'</div>' +
		'<div class="layui-upload-button layui-btn-group">' +
		'	<span class="upload-all-t layui-btn layui-btn-primary"></span>' +
		'	<button id="upload-all-t" class="upload-all layui-btn layui-btn-primary" type="button"><i class="iconfont icon-upload"></i> 一键上传</button>' +
		'	<button id="upload-file" class="upload-file layui-btn layui-btn-primary" type="button"><i class="iconfont icon-folder"></i> 选择…</button>' +
		'</div>';

	var files,
		uploadListView = $(arg.elem + ' .layui-upload-list'),
		uploadListText = $(arg.elem + ' .upload-all-t'),
		uploadNew = {};

	//layui.use(['upload2', 'element'], function() {

	var upload = layui.upload2;
	var element = layui.element;

	var uploadListIns = uploadNew.inst = upload.render({
		elem: arg.elem + ' .layui-upload-list',
		url: arg.url,
		accept: 'file',
		exts: 'jpg|png|gif|bmp|jpeg|pdf',
		size: arg.size,
		number: arg.number,
		surplus: arg.number,
		multiple: true,
		auto: false,
		drag: true,
		bindAction: '#uploadAll',
		data: arg.data,
		choose: function(obj) {
			var _this = this;
			files = obj.pushFile(); //将每次选择的文件追加到文件队列
			obj.preview(function(index, file, result) { //读取本地文件
				var tr = $([
					'<div class="layui-upload-item" id="upload-' + index + '">',
					(/\.pdf$/i.test(file.name)) ? '<div class="layui-upload-img preview-pdf-img" src="' + result + '" alt="' + file.name + '" ></div>' : '<img class="layui-upload-img" src="' + result + '" alt="' + file.name + '" />',
					'<span class="preview-t" title="' + file.name + '">' + file.name + '</span>',
					'<span class="single-upload"></span>',
					'<span class="delete"></span>',
					'<span class="preview"></span>',
					'<div class="layui-progress layui-progress-big" lay-filter="progress_' + index + '" lay-showPercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div>',
					'</div>'
				].join(''));

				tr.on('click', function(event) {
					event.stopPropagation();
				});

				//单个上传
				tr.find('.single-upload').on('click', function() {
					tr.attr('disabled', 'disabled');
					tr.find('.single-upload').css('display', 'none');
					tr.find('.layui-progress').css('display', 'block');
					obj.upload(index, file);
				});
				//删除
				tr.find('.delete').on('click', function() {
					if(files[index]) {
						delete files[index]; //删除对应的文件
						_this.surplus++;

						$.each(_this.dataNew, function(i, obj) {
							if(obj.index == index) {
								_this.dataNew.splice(i, 1);
								uploadListText.text('已添加' + _config.dataNew.length + '个文件');
								return false;
							}
						});
						setTimeout(function() {
							tr.remove();
						}, 0)
					} else {
						arg.delete && arg.delete(index, function() {
							_this.surplus++;

							$.each(_this.dataNew, function(i, obj) {
								if(obj.index == index) {
									_this.dataNew.splice(i, 1);
									uploadListText.text('已添加' + _config.dataNew.length + '个文件');
									return false;
								}
							});
							setTimeout(function() {
								tr.remove();
							}, 0)
						});
					}
				});

				//预览
				tr.find('.preview').on('click', function() {
					var urlArr = _this.dataNew,
						urlIdex = 0;
					$.each(_this.dataNew, function(i, obj) {
						if(obj.index == index) {
							urlIdex = i;
							return false;
						}
					});
					window.previewImg(urlArr, urlIdex);
				});

				uploadListView.append(tr);

				element.render('progress');
				_this.dataNew || (_this.dataNew = []);
				_this.dataNew.push({
					index: index,
					url: result,
					name: file.name
				});
				uploadListText.text('已添加' + _config.dataNew.length + '个文件');
			});

			//清除file的value(允许文件重复上传)
			(function(_this) {
				var f = _this.elem.next()[0];
				if(f.value) {
					try {
						f.value = ''; //for IE11, latest Chrome/Firefox/Opera...  
					} catch(err) {};

					if(f.value !== '') { //for IE5 ~ IE10  
						var form = document.createElement('form'),
							ref = f.nextSibling,
							p = f.parentNode;
						form.appendChild(f);
						form.reset();
						p.insertBefore(f, ref);
					}
				}
			})(_this)

		},
		done: function(res, index, upload) {
			var _this = this;

			uploadListView.find('#upload-' + index + ' .layui-progress').css('display', '');

			if(arg.done) {
				var doneArg = arg.done(res, index);
				if(doneArg) {
					if(/\.pdf$/i.test(doneArg.name)) {
						$.each(_this.dataNew, function(i, obj) {
							if(obj.index == index) {
								obj.url = doneArg.url;
								return false;
							}
						})
					}
					console.log('上传成功');
					delete files[index];
					return;
				} else {
					this.error(index, upload);
				}
			} else {
				if(res.code == 200) { //上传成功
					console.log('上传成功');
					delete files[index]; //删除文件队列已经上传成功的文件
					return;
				} else {
					this.error(index, upload);
				}
			};
		},
		error: function(index, upload) {
			uploadListView.find('#upload-' + index + ' .layui-progress').css('display', '');

			var tr = uploadListView.find('#upload-' + index);
			tr.removeAttr('disabled');
			tr.find('.single-upload').css('display', '');
			arg.error && arg.error(index);
		},
		xhr: function(index, e) { //ajax多附件上传进度条
			//计算百分比
			console.log(e);
			var percent = parseInt(100 * e.loaded / e.total);
			element.progress('progress_' + index + '', percent + '%');
		}
	});

	var _config = uploadListIns.config;

	//加入已有文件(图片)
	$.each(arg.dataOld, function(i, obj) {
		var indexSj = parseInt(Math.random() * 1e10) + '',
			tr = $([
				'<div class="layui-upload-item" id="upload-' + indexSj + '">',
				(/\.pdf$/i.test(obj.name)) ? '<div class="layui-upload-img preview-pdf-img" src="' + obj.url + '" alt="' + obj.name + '" ></div>' : '<img class="layui-upload-img" src="' + obj.url + '" alt="' + obj.name + '" />',
				'<span class="preview-t" title="' + obj.name + '">' + obj.name + '</span>',
				'<span class="delete"></span>',
				'<span class="preview"></span>',
				'</div>'
			].join(''));

		tr.on('click', function(event) {
			event.stopPropagation();
		});

		//删除
		tr.find('.delete').on('click', function() {
			arg.delete && arg.delete(indexSj, function() {
				_config.surplus++;

				$.each(_config.dataNew, function(i, obj) {
					if(obj.index == indexSj) {
						_config.dataNew.splice(i, 1);
						uploadListText.text('已添加' + _config.dataNew.length + '个文件');
						return false;
					}
				});
				setTimeout(function() {
					tr.remove();
				}, 0)
			});
		});

		//预览
		tr.find('.preview').on('click', function() {
			var urlArr = _config.dataNew,
				urlIdex = 0;
			$.each(_config.dataNew, function(i, obj) {
				if(obj.index == indexSj) {
					urlIdex = i;
					return false;
				}
			});
			window.previewImg(urlArr, urlIdex);
		});

		uploadListView.append(tr);
		_config.surplus--;

		_config.dataNew || (_config.dataNew = []);
		_config.dataNew.push({
			index: indexSj,
			url: obj.url,
			name: obj.name
		});
		uploadListText.text('已添加' + _config.dataNew.length + '个文件');
	});

	//触发一键上传
	$(arg.elem + ' #upload-all-t').on('click', function() {
		$(arg.elem + ' .layui-upload-item').not('[disabled="disabled"]').find('.single-upload').trigger('click');
	});

	//触发选择文件
	$(arg.elem + ' #upload-file').on('click', function() {
		$(arg.elem + ' .layui-upload-list').trigger('click');
	});

	//});

	return uploadNew;
};

window.previewImg = function(urlArr, index) {
	var index = index || 0;
	//轮播图
	var layerContent = '<div class="layui-carousel" id="preview-v"><div carousel-item>';
	$.each(urlArr, function(i, v) {
		if($.type(v) === 'object') {
			if(/\.pdf$/i.test(v.name)) {
				layerContent += '<div class="vertical center"><iframe class="frame-pdf-bg" style="width:80%;height:100%;" src="' + v.url + '"></iframe></div>';
			} else {
				layerContent += '<div class="vertical center preview-img-wrap"><i class="preview-img-left-btn"></i><i class="preview-img-right-btn"></i><img src="' + v.url + '"/></div>';
			}
		} else {
			if(/\.pdf$/i.test(v)) {
				layerContent += '<div class="vertical center"><iframe class="frame-pdf-bg" style="width:80%;height:100%;" src="' + v + '"></iframe></div>';
			} else {
				layerContent += '<div class="vertical center preview-img-wrap"><i class="preview-img-left-btn"></i><i class="preview-img-right-btn"></i><img src="' + v + '"/></div>';
			}
		}
	});
	layerContent += '</div></div>';
	layerContent += '<style>.layui-layer-setwin .layui-layer-close2{top: 0;right: 0;}</style>';
	layerContent += "<script>layui.use('carousel', function() { var carousel = layui.carousel; carousel.render({ elem: '#preview-v', width: '100%', height: '100%', arrow: 'always', autoplay: false, index: " + index + " }); }); $('#preview-v .preview-img-left-btn').click(function() { var the = $(this).parent(); the.attr('rotate') == '-360' && the.attr('rotate', '0'); var theRotate = parseInt(the.attr('rotate') || '0'); the.attr('rotate', (theRotate - 90 < -360) ? -360 : (theRotate - 90)); setTimeout(function() { the.attr('rotate') == '-360' && the.attr('rotate', '0') }, 600); }); $('#preview-v .preview-img-right-btn').click(function() { var the = $(this).parent(); the.attr('rotate') == '360' && the.attr('rotate', '0'); var theRotate = parseInt(the.attr('rotate') || '0'); the.attr('rotate', (theRotate + 90 > 360) ? 360 : (theRotate + 90)); setTimeout(function() { the.attr('rotate') == '360' && the.attr('rotate', '0') }, 600); });</script>";

	window.top.layer.open({
		type: 1,
		anim: -1,
		shift: -1,
		skin: 'preview-layer',
		title: false,
		resize: false,
		shade: 0,
		area: ['100%', '100%'],
		content: layerContent
	});
};